package cn.com.dhc.danlu.activity.delivery.order.viewholder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.delivery.OrderSplitListActivity;
import cn.com.dhc.danlu.activity.delivery.OrderTrackActivity;
import cn.com.dhc.danlu.activity.delivery.order.bean.OrderFuncBean;
import cn.com.dhc.danlu.activity.delivery.order.delegate.EventType;
import cn.com.dhc.danlu.activity.delivery.order.delegate.IHolderDataCallback;
import cn.com.dhc.danlu.activity.delivery.order.view.CancelReasonPopupView;
import cn.com.dhc.danlu.activity.delivery.order.view.FullScreenPriceChangeNotePopview;
import cn.com.dhc.danlu.activity.delivery.order.view.OrderFunctionView;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.bus.PayEvent;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.oper.OrderOperCancelRequest;
import cn.com.hd.mall.web.webservices.entity.request.oper.OrderOperReceiveRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.OrderLogRequest;
import cn.com.hd.mall.web.webservices.entity.response.order.OrderChangeNote;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.BTN_HAS;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.BTN_NO;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.ORDER_CANCLE;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.ORDER_DEAL_CANCLING;
import static cn.com.dhc.danlu.util.CommonConst.MyOrderConst.WAIT_RECEIVE;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-14 15:21
 * <p>
 * 订单列表项订单操作功能视图区域
 * </p>
 */
public class OrderFuncViewHolder extends BaseViewHolder<OrderFuncBean> {
    private TextView tvTotalCount; // 商品数量
    private TextView tvTotalPrice; // 商品总价

    private IHolderDataCallback callback;

    private OrderFunctionView ofvOrder;

    public OrderFuncViewHolder (View itemView, IHolderDataCallback callback) {
        super (itemView);
        this.callback = callback;
        initView ();
    }

    public OrderFuncViewHolder (View itemView) {
        super (itemView);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void bindViewData (OrderFuncBean data) {
        tvTotalPrice.setText ("￥" + CommonUtils.fenToYuan (new BigDecimal (data.getTotalPrice ())));
        String countStr = "共 " + data.getOrderMerchCount () + " 件商品";
        CommonUtils.dividerShowTextStyle (tvTotalCount, countStr, 2, countStr.length () - 4, 12, 14, R.color.color_b53636);
        boolean isShowPayBtn = data.getButtomList ().split ("")[1].equals (BTN_HAS) && !data.isPayingStatus () && data.isSupplyYjfFlag ();
        ofvOrder.refreshButton (data.getButtomList ());
    }

    private void initView () {
        tvTotalCount = (TextView) itemView.findViewById (R.id.tv_total_count);
        tvTotalPrice = (TextView) itemView.findViewById (R.id.tv_total_price);
        ofvOrder = (OrderFunctionView) itemView.findViewById (R.id.ofv_order);

        ofvOrder.setOrderOperatorCallback (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                OrderFuncBean bean = (OrderFuncBean) data;
                if (v.getId () == R.id.btn_order_pay) {
                    payAction (bean);
                } else if (v.getId () == R.id.btn_order_receive) {
                    createReceiveDialog ();
                } else if (v.getId () == R.id.btn_order_split) {
                    OrderSplitListActivity.startSelf (getContext (), bean.getOrderNo ());
                } else if (v.getId () == R.id.btn_order_change_price_note) {
                    viewOrderPriceChangeNote (bean.getOrderNo ());
                } else if (v.getId () == R.id.btn_order_track) {
                    OrderTrackActivity.startSelf (getContext (), bean.getOrderNo ());
                } else if (v.getId () == R.id.btn_order_cancel) {
                    cancelOrder (bean);
                }
            }
        });
    }

    private void cancelOrder (final OrderFuncBean bean) {
        String cancelOrderFlag = bean.getButtomList ().split ("")[4];
        if (!cancelOrderFlag.equals (BTN_NO) && !cancelOrderFlag.equals (ORDER_DEAL_CANCLING)) {
            CancelReasonPopupView popupView = new CancelReasonPopupView (getContext (), new CancelReasonPopupView.ICancelOrderListener () {
                @Override
                public void onCancel (String reason) {
                    // 取消交易请求类
                    OrderOperCancelRequest request = new OrderOperCancelRequest ();
                    request.setToken (agent.getToken ()); // 设置token
                    request.setPaymentNo (bean.getPaymentNo ()); // 设置大订单
                    request.setPayType (bean.getPayType ()); // 设置支付方式
                    // 设置cancleType
                    String cancleType = bean.getButtomList ().substring (3, 4);
                    //                final String orderStatus = tvOrderStatus.getText().toString(); // 获取显示订单状态
                    final String orderStatus = bean.getOrderStatus ();
                    request.setCancelType (cancleType);
                    request.setCancelReason (reason);
                    agent.getApi ().orderDealCancle (request).compose (OperatorUtils.defaultSchedulers ())
                            .subscribe (new GeneralBusinessObserver<BaseResponse> (getContext (), R.string.tips_order_cancel) {
                                @Override
                                protected void onSuccess (BaseResponse baseResponse) {
                                    if (orderStatus.equals ("C017")) {
                                        ToastUtil.getInstance ().show (R.string.myself_order_deal_cancle_comfirm);
                                    } else {
                                        ToastUtil.getInstance ().show (R.string.myself_order_deal_cancle_success);
                                    }
                                    dataBack (true);
                                }

                                @Override
                                protected String parseBussinessException (String code) {
                                    return code.equals ("1") ? "订单状态发生变化取消失败" : "订单取消失败";
                                }

                                @Override
                                protected void onAlertTips (String displayMessage) {
                                    ToastUtil.getInstance ().show (displayMessage);
                                }
                            });
                }
            });
            Activity activity = CommonUtils.getActivity (itemView);
            popupView.showAtLocation (activity.getWindow ().getDecorView (), Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 查看经销商改价备注
     *
     * @param orderNo
     *         订单号
     */
    private void viewOrderPriceChangeNote (String orderNo) {
        OrderLogRequest req = new OrderLogRequest ();
        req.setOrderNo (orderNo);
        req.setToken (agent.getToken ());
        agent.getApi ().getOrderChangePriceCommentInfo (req)
                .compose (OperatorUtils.<OrderChangeNote>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<OrderChangeNote> (getContext (), R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (OrderChangeNote orderChangeNote) {
                        FullScreenPriceChangeNotePopview popview = new FullScreenPriceChangeNotePopview (getContext ());
                        popview.refreshView (orderChangeNote);
                        Activity activity = CommonUtils.getActivity (itemView);
                        if (null != activity) {
                            popview.showAtLocation (activity.getWindow ().getDecorView (), Gravity.NO_GRAVITY, 0, CommonUtils.getStatusBarHeight (getContext ()));
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        super.onAlertTips (displayMessage);
                    }
                });
    }

    private void payAction (OrderFuncBean bean) {
        EventBus.getDefault ().post (new PayEvent (bean.getPaymentNo ()));
    }

    /**
     * 创建确定收货对话框
     */
    private void createReceiveDialog () {
        // 创建Builder
        ViewDialog.Builder builder = new ViewDialog.Builder (getContext ());
        // 设置信息
        builder.setMessage (R.string.myself_order_deal_receive_dialog);
        // 设置Positive按钮点击监听
        builder.setPositiveButton (R.string.btn_ok, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                dialog.dismiss ();
                receiveAction ();
            }
        });

        // 设置Negative按钮点击监听
        builder.setNegativeButton (R.string.btn_cancel, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                // 对话框关闭
                dialog.dismiss ();
            }
        });
        // 对话框不可取消
        builder.setCancelable (true);
        // 创建对话框并显示
        builder.create ().show ();
    }

    /**
     * 收货的网络请求
     */
    private void receiveAction () {
        OrderOperReceiveRequest receiveRequest = new OrderOperReceiveRequest ();
        receiveRequest.setToken (agent.getToken ());
        OrderFuncBean bean = (OrderFuncBean) data;
        receiveRequest.setOrderNo (bean.getOrderNo ());
        receiveRequest.setPaymentNo (bean.getPaymentNo ());
        receiveRequest.setPayType (bean.getPayType ());
        agent.getApi ()
                .orderReceive (receiveRequest)
                .compose (OperatorUtils.defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<BaseResponse> (itemView.getContext (), R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (BaseResponse baseResponse) {
                        dataBack (false); // 数据交互
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        return code.equals ("1") ? "订单状态发生变化，收货失败" : "收货失败";
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    /**
     * 数据交互，更新其他模块共用数据
     */
    private void dataBack (boolean isCancelOrder) {
        if (null != callback) {
            OrderFuncBean bean = (OrderFuncBean) data;
            String buttomList = bean.getButtomList ();
            String[] split = buttomList.split ("");
            StringBuilder sb = new StringBuilder ();
            String originOrderStatus = bean.getOrderStatus ();
            if (isCancelOrder) {
                boolean isChangeAll = false;
                for (int i = 1; i < split.length; i++) {
                    if (i == 4) {
                        String orderStatus = bean.getOrderStatus ();
                        // 只有待收货状态  取消订单后 才是交易取消中 其他都是已取消
                        if (orderStatus.equals (WAIT_RECEIVE)) {
                            sb.append (ORDER_DEAL_CANCLING);
                            // 订单状态不变
                        } else {
                            bean.setOrderStatus (ORDER_CANCLE);
                            sb.append ("0");
                        }
                    } else {
                        sb.append (split[i]);
                    }
                }
                //                if (isChangeAll) {
                //                    sb = new StringBuilder(sb.toString().replaceAll("\\d", "0"));
                //                }
                // 取消交易 后 如果是在线支付 butomList 第一位变为0
                //            String buttomList = bean.getButtomList ();
                //            bean.setButtomList (0 + buttomList.substring (1,buttomList.length ()));
                if (originOrderStatus.equals ("C011")) {
                    // 第一位付款按钮消失
                    sb.replace (0, 1, "0");
                } else if (originOrderStatus.equals ("C017")) {
                    // 第三位 收货按钮隐藏
                    sb.replace (2, 3, "0");
                } else if (originOrderStatus.equals ("C025")) {
                    // 支付中无法取消
                }
                bean.setButtomList (sb.toString ());
                // paymentOrderButtomList OrderFuckViewHolder 用的是第一位
                callback.onDataChanged (EventType.cancelDeal, getLayoutPosition (), bean.getGoodsLength (), sb.toString ());
            } else {
                for (int i = 1; i < split.length; i++) {
                    if (i == 3) {
                        sb.append (BTN_NO);
                    } else {
                        sb.append (split[i]);
                    }
                }
                bean.setButtomList (sb.toString ());
                // 点击收货后 将交易状态改为已完成
                callback.onDataChanged (EventType.receiveGoods, getLayoutPosition (), bean.getGoodsLength (), sb.toString ());
            }
        }
    }
}
